package com.uni.config;

import com.uni.util.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * 初始化公钥和私钥
 *
 * 配置：
 *       jwt:
 *           secret: sc@Login(Auth}*^31)&czxy% # 登录校验的明文
 *           pubKeyPath: D://rsa//rsa.pub # 公钥地址
 *           priKeyPath: D://rsa//rsa.pri # 私钥地址
 *           expire: 30 # 过期时间,单位分钟
 */
@Slf4j
@Data
@PropertySource("classpath:application.yml")
@ConfigurationProperties(prefix = "jwt")
@Configuration
public class JWTProperties {

    private String secret; // 密文

    private String pubKeyPath;// 公钥

    private String priKeyPath;// 私钥

    private Integer expire;// token过期时间

    private String[] skipAuthUrls; //跳过的url

    private PublicKey publicKey; // 公钥

    private PrivateKey privateKey; // 私钥

    //被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行，并且只会被服务器调用一次
    @PostConstruct
    public void init() {
        try {
            log.info("公钥地址: " + pubKeyPath);
            log.info("私钥地址: " + priKeyPath);
            File pubKey = new File(pubKeyPath);
            File priKey = new File(priKeyPath);

            if (!pubKey.exists() || !priKey.exists()) {
                // 生成公钥和私钥并写入文件
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }
            // 获取公钥和私钥
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥和私钥失败! " + e);
            throw new RuntimeException();
        }
    }
}
